import 'dart:io';
import 'dart:math';

import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_list_item_bean.dart';
import 'package:e_reception_flutter/ui/company/choose_city/widgets/choose_city_tabs_and_pages_widget.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_displaymode/flutter_displaymode.dart';
import 'package:timezone/timezone.dart';
import 'package:vg_base/vg_log_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:timezone/timezone.dart' as tz;

class VgToolUtils {
  static Random sRandom = Random();

  ///移除所有焦点
  static void removeAllFocus(BuildContext context) {
    if (context == null) {
      return;
    }
    // final FocusScopeNode focusScope = FocusScope.of(context);
    // if(focusScope != null && focusScope.hasFocus){
    //   focusScope.unfocus();
    // }
    ///触摸收起键盘
    FocusScope.of(context).requestFocus(FocusNode());
  }

  ///三位数
  static String threeDigits(int n) {
    if (n == null || n < 0) {
      return "000";
    }
    if (n >= 100) return "$n";
    if (n >= 10) return "0$n";
    return "00${n ?? 0}";
  }

  ///两位数
  static String twoDigits(int n) {
    if (n == null || n < 0) {
      return "00";
    }
    if (n >= 10) return "$n";
    return "0$n";
  }

  ///获取随机bool类型
  static bool getRandomBool() {
    return sRandom.nextBool();
  }

  ///设置刷新率模式
  static void proccessRefreshMode() async {
    //非android无需设置刷新率
    if (!Platform.isAndroid) {
      return;
    }
    try {
      final DisplayMode currentMode = await FlutterDisplayMode.current;
      if (currentMode == null ||
          currentMode.width == null ||
          currentMode.height == null) {
        LogUtils.d("获取当前分辨率和刷新率失败");
        return;
      }
      final List<DisplayMode> modes = await FlutterDisplayMode.supported;
      modes.forEach((a) => print("支持：" + a.toString()));
      if (modes == null || modes.isEmpty) {
        return;
      }
      //比当前更高模式
      DisplayMode moreCurrentMode = currentMode;
      for (DisplayMode item in modes) {
        if (item == null || item.width == null || item.height == null) {
          continue;
        }
        if (item.width == moreCurrentMode.width &&
            item.height == moreCurrentMode.height &&
            item.refreshRate > moreCurrentMode.refreshRate) {
          moreCurrentMode = item;
        }
      }
      if (moreCurrentMode == null) {
        print("调节刷新率失败(相等)：${currentMode?.toString()}");
        return;
      }
      // await FlutterDisplayMode.setDefaultMode();
      //设置高刷新
      print("手动设置刷新率： ${moreCurrentMode?.toString()}");
      await FlutterDisplayMode.setMode(moreCurrentMode);

      /// On OnePlus 7 Pro:
      /// #1 1080x2340 @ 60Hz
      /// #2 1080x2340 @ 90Hz
      /// #3 1440x3120 @ 90Hz
      /// #4 1440x3120 @ 60Hz
      /// On OnePlus 8 Pro:
      /// #1 1080x2376 @ 60Hz
      /// #2 1440x3168 @ 120Hz
      /// #3 1440x3168 @ 60Hz
      /// #4 1080x2376 @ 120Hz
    } on PlatformException catch (e) {
      print("调节刷新率异常：${e?.toString()}");

      /// e.code =>
      /// noAPI - No API support. Only Marshmallow and above.
      /// noActivity - Activity is not available. Probably app is in background
    }
  }

  ///获取屏幕宽度
  static double getScreenWidth() {
    return ScreenUtils.screenW(AppMain.context);
  }

  ///获取屏幕高度
  static double getScreenHeight() {
    return ScreenUtils.screenH(AppMain.context);
  }

  ///秒时间戳(几分前，昨天啥的)
  static String getTimestrampStr(int timeStramp) {
    if (timeStramp == null || timeStramp <= 0) {
      return null;
    }
    //转成毫秒
    return VgDateTimeUtils.getFormatTimeStr(timeStramp);
  }

  static TZDateTime getTZDateTime(DateTime dateTime){
    // 根据指定时区创建时区信息
    var location = tz.getLocation(TIME_ZONE);
    return tz.TZDateTime.from(dateTime, location);
  }

  ///获取小时和分钟字符串
  static String getHourAndMinuteStr(int timeStramp) {
    if (timeStramp == null || timeStramp <= 0) {
      return null;
    }
    //转成毫秒
    int tmpTimeStramp = timeStramp * 1000;
    DateTime dateTime = DateUtil.getDateTimeByMs(tmpTimeStramp);
    if (dateTime == null) {
      return null;
    }

    // 根据指定时区创建时区信息
    var tzDateTime = getTZDateTime(dateTime);

    return twoDigits(tzDateTime.hour).toString() +
        ":" +
        twoDigits(tzDateTime.minute).toString();
  }

  ///获取格式化字符串
  ///em: 2020-12-02 12:32
  static String getHourAndMinuteByFormatStr(
    int timeStramp, {
    String zhAndTimeSplit = "",
    String yearOrMonthOrDaySplit,
    bool isShowCompleteYear = false,
  }) {
    if (timeStramp == null || timeStramp <= 0) {
      return null;
    }
    return VgDateTimeUtils.getFormatTimeStr(timeStramp,
        zhAndTimeSplit: zhAndTimeSplit,
        yearOrMonthOrDaySplit: yearOrMonthOrDaySplit,
        isShowCompleteYear: isShowCompleteYear);
  }

  ///获取月和日字符串
  static String getMonthAndDayStr(int timeStramp) {
    if (timeStramp == null || timeStramp <= 0) {
      return null;
    }
    //转成毫秒
    int tmpTimeStramp = timeStramp * 1000;
    DateTime dateTime = DateUtil.getDateTimeByMs(tmpTimeStramp);
    if (dateTime == null) {
      return null;
    }
    // 根据指定时区创建时区信息
    var tzDateTime = getTZDateTime(dateTime);

    return twoDigits(tzDateTime.month).toString() +
        "月" +
        twoDigits(tzDateTime.day).toString() +
        "日";
  }

  ///时间差距小时/分钟
  ///待封装格式类型
  static String getDifferenceTimeStr(int firstTime, int secondTime) {
    if (firstTime == null ||
        firstTime <= 0 ||
        secondTime == null ||
        secondTime <= 0) {
      return null;
    }
    // int tmpFirstTime = firstTime * 1000;
    // int tmpSecondTime = secondTime * 1000;
    int tmpFirstTime = (firstTime - DateUtil.getDateTimeByMs(firstTime * 1000).second) * 1000;
    int tmpSecondTime = (secondTime - DateUtil.getDateTimeByMs(secondTime * 1000).second) * 1000;
    int sub;
    if (tmpFirstTime > tmpSecondTime) {
      sub = tmpFirstTime - tmpSecondTime;
    } else {
      sub = tmpSecondTime - tmpFirstTime;
    }
    if (sub == null || sub < 0) {
      return null;
    }
    int hour = ((sub / 1000) / 3600).floor();
    int minute = ((sub - (hour * 3600 * 1000)) / 1000 / 60).ceil();
    int second =
        ((sub - (hour * 3600 * 1000) - (minute * 60 * 1000)) / 1000).floor();
    // if(second != null && second >0){minute++;}
    if ((hour == null || hour <= 0) && (minute == null || minute <= 0)) {
      if(second < 60 && second != 0){
        return null;
        // if(tmpFirstTime > tmpSecondTime){
        //   return null;
        // }
        // return "1分钟";
      }
      return null;
    }
    if (hour == null || hour <= 0) {
      return "$minute分钟";
    }
    if(hour>=0 && minute == 0){
      return "$hour小时";
    }
    if(hour>=0 && minute == 60){
      if(second<=(-30)){
        return "$hour小时${minute-1}分钟";
      }
      return "${hour+1}小时";
    }
    return "$hour小时${minute}分钟";
  }

  ///两个字符串拼串
  static String getTwoSplitStr(String firstStr, String secondStr,
      {String split = "·"}) {
    if (StringUtils.isNotEmpty(firstStr) && StringUtils.isNotEmpty(secondStr)) {
      return firstStr + split + secondStr;
    }
    if (StringUtils.isNotEmpty(firstStr)) {
      return firstStr;
    }
    if (StringUtils.isNotEmpty(secondStr)) {
      return secondStr;
    }
    return null;
  }

  ///是否是访客分组
  static bool isVisitorGroup(String groupId, String groupName) {
    if (StringUtils.isEmpty(groupName)) {
      return false;
    }
    if (groupName == "访客") {
      return true;
    }
    return false;
  }

  ///是否显示最大时间
  static bool isShowMaxTime(int minTime, int maxTime) {
    if (minTime == null || minTime <= 0 || maxTime == null || maxTime <= 0) {
      return false;
    }
    if (minTime >= maxTime) {
      return false;
    }
    return true;
  }

  static String showMemoryStr(int kbValue) {
    if (kbValue == null || kbValue <= 0) {
      return "0KB";
    }
    if (kbValue < 1024) {
      return "${kbValue}KB";
    }
    if (kbValue < 1024 * 1024) {
      return "${(kbValue / 1024).floor()}MB";
    }
    if (kbValue < 1024 * 1024 * 1024) {
      return "${(kbValue / 1024 / 1024).floor()}GB";
    }
    return "${kbValue}KB";
  }

  ///判断是不是手机位数（以后可以加正则表达式判断）
  static bool isPhone(String phone) {
    if (phone == null || phone.isEmpty) {
      return false;
    }
    //因为有的编辑框显示11位，但实际从TextEditController获取的是超过12位
    //需保存的时候截断11位
    if (phone.length >= DEFAULT_PHONE_LENGTH_LIMIT) {
      return true;
    }
    return false;
  }


  ///退出app
  static Future<void> exitApp() async {
    if(Platform.isIOS){
      exit(0);
    }else if(Platform.isAndroid){
      await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    }
  }

  ///获取上海时区的当前时间
  static DateTime getShangHaiTimeZoneDateTime(){
    final DateTime nowDateTime = DateTime.now();
    TZDateTime nowInShanghai = getTZDateTime(nowDateTime);
    return DateTime(nowInShanghai.year, nowInShanghai.month, nowInShanghai.day);
  }

  ///获取当前时区的当前时间
  static DateTime getCurrentDateTime(){
    final DateTime nowDateTime = DateTime.now();
    return DateTime(nowDateTime.year, nowDateTime.month, nowDateTime.day);
  }

  ///获取最新/最大的日期，
  ///如果时间在上海之后，根据当前时区时间返回实际的，
  ///如果时间在上海之前，返回上海的日期
  static DateTime getMaxTimeZoneDateTime(){
    final DateTime now = DateTime.now();
    final DateTime nowDateTime = DateTime(now.year, now.month, now.day);
    var nowInShanghai = getShangHaiTimeZoneDateTime();
    // 比较当前时间与东8区时间
    DateTime finalTime;
    if (nowDateTime.isBefore(nowInShanghai)) {
      finalTime = nowInShanghai;
    } else {
      finalTime = nowDateTime;
    }
    return finalTime;
  }

  ///获取日期串
  static String getDateStr(DateTime selectDateTime){
    if(selectDateTime == null){
      return "-";
    }
    var currentDateTime = getCurrentDateTime();

    StringBuffer stringBuffer = StringBuffer();

    if(currentDateTime.year == selectDateTime.year) {
      if (currentDateTime == selectDateTime) {
        stringBuffer.write("今天 ");
      } else if (currentDateTime == selectDateTime.add(Duration(days: 1))) {
        stringBuffer.write("昨天 ");
      } else if (currentDateTime == selectDateTime.add(Duration(days: 2))) {
        stringBuffer.write("前天 ");
      }
    }else{
      stringBuffer.write("${selectDateTime.year}年");
    }

    stringBuffer.write("${selectDateTime.month}月${selectDateTime.day}日");
    return stringBuffer.toString();
  }


}
